﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DoeObjects;
using DoeLibsMVC.Models;

namespace DoeLibsMVC.Controllers.api
{
    public class TopicController : ApiController
    {
		public List<TopicModel> Get(string q = null)
		{
			List<Topic> topics = null;
			if (string.IsNullOrEmpty(q))
			{
				topics = Topic.getAll();
			}
			else
			{
				topics = new List<Topic>();
				topics = Topic.getByName(q, true);
				topics = topics.Distinct().ToList();
			}

			List<TopicModel> models = new List<TopicModel>();

			foreach (Topic topic in topics)
			{
				TopicModel tm = new TopicModel();
				tm.Topic = topic;
				tm.Titles = Title.getTitlesFromTopic(topic.TopicId);

				models.Add(tm);
			}
			return models;
		}

        public HttpResponseMessage Get(int id)
        {
            Topic topic = Topic.getByTopicId(id);
            if (topic == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            TopicModel tm = new TopicModel();
            tm.Topic = topic;
            tm.Titles = Title.getTitlesFromTopic(id);

            return Request.CreateResponse<TopicModel>(HttpStatusCode.OK, tm);
        }

        /// <summary>
        /// edit a topic
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [DoeLibsMVC.Filter.ValidateModel]
        [Security.BasicAuthorize(Roles = Security.UserCategoryHelper.STAFF_CATEGORY)]
        public HttpResponseMessage Put(int id, EditTopicModel model)
        {
            Topic topic = Topic.getByTopicId(id);

            if (topic != null)
            {
                topic.TopicName = model.TopicName;

                if (topic.save())
                {
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.InternalServerError);
                }
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
        }
    }
}
